package auto.app.util;

import auto.app.exetion.HibernateExetion;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpMethod;
import org.springframework.validation.BindingResult;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {

    public static void bindingResult(BindingResult bindingResult) throws HibernateExetion {
        if (bindingResult != null && bindingResult.hasErrors()) {
            StringBuilder errorMessageBuilder = new StringBuilder();
            bindingResult.getAllErrors().forEach(error -> errorMessageBuilder.append("[").append(error.getObjectName())
                    .append("-").append(error.getDefaultMessage()).append("]"));
            throw new HibernateExetion(500, errorMessageBuilder.toString());
        }
    }

    public static <T> List<T> copyList(List list, Class<T> clazz) {
        ArrayList list1 = new ArrayList();
        try {
            for (Object o : list) {
                T t = clazz.newInstance();
                BeanUtils.copyProperties(o, t);
                list1.add(t);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return list1;
    }

    public static <T> T copyOne(Object object, Class<T> clazz) {
        T t = null;
        try {
            t = clazz.newInstance();
            BeanUtils.copyProperties(object, t);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return t;
    }

    //date类型转换为yyyy-MM-dd HH:mm:ss格式日期
    public static String dateparse(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    //yyyy-MM-dd HH:mm:ss格式日期轉換為date類型
    public static Date dateparse(String date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = sdf.parse(date);
        return parse;
    }

    //请求方式的判断
    public static HttpMethod getMethod(String method) {
        switch (method) {
            case "POST":
                return HttpMethod.POST;
            case "HEAD":
                return HttpMethod.HEAD;
            case "PUT":
                return HttpMethod.PUT;
            case "PATCH":
                return HttpMethod.PATCH;
            case "DELETE":
                return HttpMethod.DELETE;
            case "OPTIONS":
                return HttpMethod.OPTIONS;
            case "TRACE":
                return HttpMethod.TRACE;
            default:
                return HttpMethod.GET;
        }
    }

    //请求类型处理
    public static HashMap<String, String> getType(String Type) {
        HashMap<String, String> hashMap = new HashMap<>();
        switch (Type) {
            case "json":
                hashMap.put("content-type", "application/json;charset=UTF-8");
                return hashMap;
            default:
                hashMap.put("content-type", "application/x-www-form-urlencoded");
                return hashMap;
        }
    }

    //根据情况来写 还需要更改
    //根据key和json字符串取出特定的value
    public static String findJosnValue(String key, String josn) {
        String regex = "\"" + key + "\":(\"(.*?)\"|(\\d*))";
        Matcher matcher = Pattern.compile(regex).matcher(josn);
        String value = null;
        if (matcher.find()) {
            value = matcher.group().split("\\:")[1].replace("\"", "").trim();
            System.out.println(value);
        }
        return value;
    }

    //如果存在多个值 提取成一个List数组
    public static HashMap<Integer,String> findJosnValueList(String key, String josn) {
        String regex = "\"" + key + "\":(\"(.*?)\"|(\\d*))";
        Matcher matcher = Pattern.compile(regex).matcher(josn);
        HashMap<Integer,String>integerStringHashMap=new HashMap<>();
        int i=0;
        while (matcher.find()) {
            String  value = matcher.group().split("\\:")[1].replace("\"", "").trim();
            integerStringHashMap.put(i,value);
            i++;
        }
        return integerStringHashMap;
    }
    //object对象转list集合
    public static <T> List<T> castList(Object obj, Class<T> clazz)
    {
        List<T> result = new ArrayList<T>();
        if(obj instanceof List<?>)
        {
            for (Object o : (List<?>) obj)
            {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }

//    public static Map<String, Object> json2Map(String jsonStr) {
//        Map<String, Object> map = new HashMap<>();
//        if(jsonStr != null && !"".equals(jsonStr)){
//            //最外层解析
//            JSONObject json = JSONObject.fromObject(jsonStr);
//            for (Object k : json.keySet()) {
//                Object v = json.get(k);
//                //如果内层还是数组的话，继续解析
//                if (v instanceof JSONArray) {
//                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
//                    Iterator<JSONObject> it = ((JSONArray) v).iterator();
//                    while (it.hasNext()) {
//                        JSONObject json2 = it.next();
//                        list.add(json2Map(json2.toString()));
//                    }
//                    map.put(k.toString(), list);
//                } else {
//                    map.put(k.toString(), v);
//                }
//            }
//            return map;
//        }else{
//            return null;
//        }
//    }

}
